import React from 'react';
import { message, Input } from 'antd';
import cn from 'classnames';
import styles from './index.less';

let id;
const validators = [
    {
        validator: link => link && link.length <= 2000,
        message: '不可超过2000字'
    },
    {
        validator: link =>
            // /^(ht|f)tps?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?([a-zA-Z0-9_-]|#|%|\)|\()(\?)?)*)*$/i
            /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/i.test(link),
        message: '请输入有效网址'
    }
];

const getValidateError = link => {
    let msg;
    if (!link) {
        return msg;
    }
    validators.some(item => {
        if (!item.validator(link)) {
            msg = item.message;
            return true;
        }
        return false;
    });
    return msg;
};
const RelativeLink = React.forwardRef(({ value, onChange }, childRef) => {
    const handleAdd = () => {
        if (value && value.length < 20) {
            if (!id) id = value.length || 0;
            id += 1;
            onChange([...value, { key: id }]);
        } else {
            message.error('上限20个');
        }
    };
    const handleOnChange = (e, key) => {
        onChange(
            value.map(it => {
                if (it.key === key) {
                    return { ...it, link: e.target.value };
                }
                return it;
            })
        );
    };
    const handleDelete = key => {
        onChange(value.filter(it => it.key !== key));
    };
    React.useImperativeHandle(childRef, () => ({
        getValidateError
    }));
    return (
        <>
            <span
                style={{
                    color: value.length < 20 ? '#FFA22D' : 'rgba(0, 0, 0, 0.25)',
                    cursor: 'pointer'
                }}
                onClick={handleAdd}
            >
                添加链接
            </span>
            {value.map(item => (
                <div
                    key={item.key}
                    style={{ position: 'relative' }}
                    className={cn({
                        [styles.success]: !getValidateError(item.link)
                    })}
                >
                    <Input
                        style={{ width: '100%', paddingRight: '30px', boxSizing: 'border-box' }}
                        value={item.link}
                        onChange={e => handleOnChange(e, item.key)}
                    />
                    <i
                        className="icon iconfont iconshanchu"
                        style={{
                            position: 'absolute',
                            right: '12px',
                            top: '0',
                            cursor: 'pointer',
                            color: '#333333'
                        }}
                        onClick={() => handleDelete(item.key)}
                    />
                </div>
            ))}
        </>
    );
});

export default RelativeLink;
